package cn.hnu.controller;


import cn.hnu.domain.Users;
import cn.hnu.domain.dto.EmailRequest;
import cn.hnu.domain.dto.RegisterRequest;
import cn.hnu.domain.vo.BaseResult;
import cn.hnu.service.EmailService;
import cn.hnu.service.UsersService;
import cn.hnu.utils.JwtUtils;
import cn.hnu.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;
import java.util.regex.Pattern;

/**
 * 认证控制器，处理与用户认证相关的请求
 */
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {

    private final UsersService usersService;
    private final EmailService emailService;
    private final RedisUtil redisUtil;

    /**
     * 登录
     * @return token
     */
    @PostMapping("/login")
    public BaseResult login(@RequestBody Users users) {
        Users user = usersService.findUser(users.getUsername(), users.getPassword());
        if(user == null) {
            return BaseResult.fail("用户名或密码错误");
        }
        // 登录成功返回token
        String token = JwtUtils.sign(user.getId(), user.getUsername(), user.getRoleId());
        return BaseResult.ok(token);
    }
    /**
     * 注册
     * @param request
     * @param registerToken
     * @return
     */
    @PostMapping("/register")
    public BaseResult register(@RequestBody RegisterRequest request,
                               @RequestHeader("X-Register-Token") String registerToken) {

        // 验证注册令牌
        String email = (String) redisUtil.get("registerToken:" + registerToken);
        if (email == null) {
            return BaseResult.fail("请先完成邮箱验证");
        }
        if (!email.equals(request.getEmail())) {
            return BaseResult.fail("邮箱不匹配");
        }

        // 验证通过后删除令牌
        redisUtil.delete("registerToken:" + registerToken);
        // 注册
        boolean flag = usersService.register(request.toUsers());
        if(!flag) {
            return BaseResult.fail("注册失败");
        }
        return BaseResult.ok("注册成功!");
    }



    /**
     * 发送邮箱
     * @param request
     * @return
     */
    @PostMapping("/sendEmail")
    public BaseResult sendEmail(@RequestBody EmailRequest request) {
        // 先查缓存，如果有则不发送
        if(redisUtil.get("activeCode:" + request.getEmail()) != null) {
            return BaseResult.fail("激活码已发送，请稍后再试");
        }
        String activeCode = UUID.randomUUID().toString().substring(0, 6); // 生成激活码
        String email = request.getEmail();
        // 1. 验证邮箱格式
        if (!isValidEmail(email)) {
            throw new IllegalArgumentException("邮箱格式不正确");
        }

        // 发送邮件
        emailService.sendSimpleEmail(email, "AlphaExam账号激活", "您的激活码为：" + activeCode+" 请尽快激活，60秒内有效");


        // 将激活码保存到缓存中，后续激活时验证（120s
        redisUtil.set("activeCode:" + email, activeCode, 120);
        return BaseResult.ok("激活码发送成功，请前往邮箱查看");
    }

    private boolean isValidEmail(String email) {
        String emailRegex = "^[A-Za-z0-9+_.-]+@(.+)$";
        return Pattern.matches(emailRegex, email);
    }

    /**
     * 校对激活码
     * @return
     */
    @PostMapping("/vetifyCode")
    public BaseResult vetifyCode(@RequestBody EmailRequest request) {
        String email = request.getEmail();
        String activeCode = request.getActiveCode();
        // 从缓存中获取激活码
         String code = (String) redisUtil.get("activeCode:" + email);
         if(code == null || !code.equals(activeCode)) {
             return BaseResult.fail("激活码错误或已过期");
         }
        // 生成注册令牌（JWT或UUID）
        String registerToken = UUID.randomUUID().toString();
        // 将注册令牌与邮箱绑定，有效期10分钟
        redisUtil.set("registerToken:" + registerToken, email, 600);

        // 删除激活码，防止重复使用
        redisUtil.delete("activeCode:" + email);

        return BaseResult.ok(registerToken);
    }





}
